package com.offics.loan.domain.service;

import com.offics.loan.domain.entity.User;
import com.offics.loan.domain.entity.UserInfo;
import com.offics.loan.domain.repository.UserInfoRepository;
import com.offics.loan.domain.repository.UserRepository;
import com.offics.loan.infrastructure.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 用户领域服务
 */
@Service
@RequiredArgsConstructor
public class UserDomainService {

    private final UserRepository userRepository;
    private final UserInfoRepository userInfoRepository;
    private final PasswordEncoder passwordEncoder;

    /**
     * 注册用户
     *
     * @param user 用户
     * @return 注册后的用户
     */
    @Transactional(rollbackFor = Exception.class)
    public User register(User user) {
        // 检查用户名是否存在
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new BusinessException("用户名已存在");
        }

        // 检查手机号是否存在
        if (user.getPhone() != null && userRepository.existsByPhone(user.getPhone())) {
            throw new BusinessException("手机号已存在");
        }

        // 检查邮箱是否存在
        if (user.getEmail() != null && userRepository.existsByEmail(user.getEmail())) {
            throw new BusinessException("邮箱已存在");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        // 设置状态为启用
        user.setStatus(1);
        // 保存用户
        User savedUser = userRepository.saveAndReturn(user);

        // 创建用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(savedUser.getId());
        userInfoRepository.save(userInfo);

        return savedUser;
    }

    /**
     * 更新用户
     *
     * @param user 用户
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean update(User user) {
        // 检查用户是否存在
        Optional<User> optionalUser = userRepository.findById(user.getId());
        if (optionalUser.isEmpty()) {
            throw new BusinessException("用户不存在");
        }

        User existingUser = optionalUser.get();

        // 检查用户名是否存在
        if (!existingUser.getUsername().equals(user.getUsername()) && userRepository.existsByUsername(user.getUsername())) {
            throw new BusinessException("用户名已存在");
        }

        // 检查手机号是否存在
        if (user.getPhone() != null && !user.getPhone().equals(existingUser.getPhone()) && userRepository.existsByPhone(user.getPhone())) {
            throw new BusinessException("手机号已存在");
        }

        // 检查邮箱是否存在
        if (user.getEmail() != null && !user.getEmail().equals(existingUser.getEmail()) && userRepository.existsByEmail(user.getEmail())) {
            throw new BusinessException("邮箱已存在");
        }

        // 如果密码不为空，则加密密码
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            user.setPassword(existingUser.getPassword());
        }

        return userRepository.update(user);
    }

    /**
     * 更新用户信息
     *
     * @param userInfo 用户信息
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserInfo(UserInfo userInfo) {
        // 检查用户是否存在
        Optional<User> optionalUser = userRepository.findById(userInfo.getUserId());
        if (optionalUser.isEmpty()) {
            throw new BusinessException("用户不存在");
        }

        // 检查用户信息是否存在
        Optional<UserInfo> optionalUserInfo = userInfoRepository.findByUserId(userInfo.getUserId());
        if (optionalUserInfo.isEmpty()) {
            // 如果不存在，则创建
            userInfo.setId(null);
            userInfoRepository.save(userInfo);
            return true;
        } else {
            // 如果存在，则更新
            userInfo.setId(optionalUserInfo.get().getId());
            return userInfoRepository.update(userInfo);
        }
    }

    /**
     * 修改密码
     *
     * @param userId 用户ID
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        // 检查用户是否存在
        Optional<User> optionalUser = userRepository.findById(userId);
        if (optionalUser.isEmpty()) {
            throw new BusinessException("用户不存在");
        }

        User user = optionalUser.get();

        // 检查旧密码是否正确
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new BusinessException("旧密码不正确");
        }

        // 更新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        return userRepository.update(user);
    }

    /**
     * 重置密码
     *
     * @param userId 用户ID
     * @param newPassword 新密码
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean resetPassword(Long userId, String newPassword) {
        // 检查用户是否存在
        Optional<User> optionalUser = userRepository.findById(userId);
        if (optionalUser.isEmpty()) {
            throw new BusinessException("用户不存在");
        }

        User user = optionalUser.get();

        // 更新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        return userRepository.update(user);
    }

    /**
     * 启用用户
     *
     * @param userId 用户ID
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean enable(Long userId) {
        // 检查用户是否存在
        Optional<User> optionalUser = userRepository.findById(userId);
        if (optionalUser.isEmpty()) {
            throw new BusinessException("用户不存在");
        }

        User user = optionalUser.get();
        user.setStatus(1);
        return userRepository.update(user);
    }

    /**
     * 禁用用户
     *
     * @param userId 用户ID
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean disable(Long userId) {
        // 检查用户是否存在
        Optional<User> optionalUser = userRepository.findById(userId);
        if (optionalUser.isEmpty()) {
            throw new BusinessException("用户不存在");
        }

        User user = optionalUser.get();
        user.setStatus(0);
        return userRepository.update(user);
    }

    /**
     * 删除用户
     *
     * @param userId 用户ID
     * @return 是否成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long userId) {
        // 检查用户是否存在
        Optional<User> optionalUser = userRepository.findById(userId);
        if (optionalUser.isEmpty()) {
            throw new BusinessException("用户不存在");
        }

        // 删除用户信息
        userInfoRepository.deleteByUserId(userId);

        // 删除用户
        return userRepository.deleteById(userId);
    }
}
